﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Configuration;
using Abp.Extensions;
using Abp.Json;
using Abp.Linq.Extensions;
using Abp.Runtime.Caching;
using Abp.Timing;
using Mt.Site.Application.ContentManagement.FrontEnd.Dto;
using Mt.Site.Application.Dto.Add;
using Mt.Site.Core.Configuration;
using Mt.Site.Core.ContentManagement;
using Mt.Site.Core.ContentManagement.Entities;
using Mt.Site.Core.Navigations;
using Mt.Site.Core.Storage;
using Mt.Site.Core.Url;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Text.RegularExpressions;

namespace Mt.Site.Application.ContentManagement.FrontEnd
{
    public class ContentFrontEndAppService : MtSiteFrontendAppServiceBase, IContentFrontEndAppService
    {
        private readonly IMenuStore _menuStore;                             //栏目信息
        private readonly IContentFrontendManager _contentFrontendManager;   //Core层接口
        private readonly IFileObjectManager _fileObjectManager;             //后台上传图片附件接口
        private readonly IPageUrlHelper _urlHelper;                         //栏目信息接口
        private readonly IWebUrlService _WebUrlService;
        //private readonly IRepository<ContentBase, Guid> _contentBaseRepository;

        private readonly ICacheManager _cacheManager;

        private ITypedCache<string, PagedResultDto<_ContentListDto>> PagedListCache
            => _cacheManager.GetCache<string, PagedResultDto<_ContentListDto>>(ApiCacheNames.ContentPagedList);

        public ContentFrontEndAppService(IMenuStore menuStore,
            IContentFrontendManager contentFrontendManagerr,
            IPageUrlHelper urlHelper,
            IWebUrlService WebUrlService,
            IFileObjectManager fileObjectManager,
            //IRepository<ContentBase, Guid> contentBaseRepository,
            ICacheManager cacheManager)
        {
            _contentFrontendManager = contentFrontendManagerr;
            _fileObjectManager = fileObjectManager;
            _urlHelper = urlHelper;
            _menuStore = menuStore;
            _WebUrlService = WebUrlService;
            //_contentBaseRepository = contentBaseRepository;
            _cacheManager = cacheManager;
        }


        #region 基础方法
        /// <summary>
        /// 获取内容详情页
        /// </summary>
        /// <param name="input">内容的输入模型</param>
        /// <returns>如果未找到返回空；文件数据的字典如果没数据则为new的空数据</returns>
        public async Task<_ContentDto> _GetContentAsync(_ContentInput input)
        {
            return await _GetContentAsync(input, null);
        }

        [RemoteService(IsEnabled = false, IsMetadataEnabled = false)]
        public async Task<_ContentDto> _GetContentAsync(_ContentInput input, Func<_ContentDto,bool> func)
        {
            var result = await _contentFrontendManager.GetContentByIdAsync<_ContentDto>(input.Id);
            if (result != null)
            {
                if (!string.IsNullOrEmpty(result.Body))
                {
                    result.Body = result.Body.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                if (!string.IsNullOrEmpty(result.Body2))
                {
                    result.Body2 = result.Body2.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                input.RelateId = result.RelateId;
                result.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(result.MenuId)).DisplayName();   // 栏目名称
                result.ListUrl = await _urlHelper.GetUrl(result.MenuId);                                        // 列表页URL
                result.LinkUrl = await _urlHelper.GetUrl(result.MenuId, result.AuxiliaryId);                     // 详情页URL
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    result.DicPic = await _GetPicOrFileDic(input.PicKeys, result.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    //result.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, result.Id, input.PicListMaxCount);
                    var list_count = input.PicListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        result.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, result.Id, max);
                    }
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    result.DicFile = await _GetPicOrFileDic(input.FileKeys, result.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    //result.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, result.Id, input.FileListMaxCount);
                    var list_count = input.FileListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        result.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, result.Id, max);
                    }
                }
                // 展示上下页
                if (input.ShowPreAndNextInfo)
                {
                    var pre_nex_input = new _PreAndNextInput
                    {
                        Id = result.Id,
                        MenuId = result.MenuId,
                        RelateId = input.RelateId,
                        Sorting = input.Sorting
                    };
                    result.PreAndNext = await _GetPreAndNextContentAsync(pre_nex_input);
                }
            }
            return result;
        }

        [AbpAuthorize]
        public async Task<_ContentDto> _GetContentPreviewAsync(_ContentInput input)
        {
            var result = await _contentFrontendManager.GetContentByIdPreaViewAsync<_ContentDto>(input.Guid.Value);
            if (result != null)
            {
                result.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(result.MenuId)).DisplayName();   // 栏目名称
                result.ListUrl = await _urlHelper.GetUrl(result.MenuId);                                        // 列表页URL
                result.LinkUrl = await _urlHelper.GetUrl(result.MenuId, result.AuxiliaryId);                     // 详情页URL
                if (!string.IsNullOrEmpty(result.Body))
                {
                    result.Body = result.Body.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                if (!string.IsNullOrEmpty(result.Body2))
                {
                    result.Body2 = result.Body2.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    result.DicPic = await _GetPicOrFileDic(input.PicKeys, result.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    //item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, input.PicListMaxCount);
                    var list_count = input.PicListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        result.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, result.Id, max);
                    }
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    result.DicFile = await _GetPicOrFileDic(input.FileKeys, result.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    //item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, input.FileListMaxCount);
                    var list_count = input.FileListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        result.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, result.Id, max);
                    }
                }
                // 展示上下页
                if (input.ShowPreAndNextInfo)
                {

                    var pre_nex_input = new _PreAndNextInput();
                    pre_nex_input.Id = result.Id;
                    pre_nex_input.MenuId = result.MenuId;
                    pre_nex_input.RelateId = input.RelateId;
                    pre_nex_input.Sorting = input.Sorting;
                    if (input.PicKeys != null)
                    {
                        var PicKeys = input.PicKeys.Split(',')[0];
                        pre_nex_input.picKey = PicKeys;
                    }

                    result.PreAndNext = await _GetPreAndNextContentAsync(pre_nex_input);
                }
            }
            return result;

        }

        /// <summary>
        /// 获取第一条数据
        /// </summary>
        /// <param name="input"></param>
        ///（修改）
        /// 创建日期：2020年04月29日
        /// 创建人：WUJB
        /// 递归遍历所有子级，多个图片对应调取数量
        /// <returns></returns>
        public async Task<_ContentDto> _FirstOrDefaultContent(_FirstContentInput input) {
            
            // 是否查找子栏目
            if (input.IsAllSon)
            {
                if (input.MenuIdList != null)
                {
                    //递归遍历所有子级
                    List<long> Templist = new List<long>();
                    foreach (var menuId in input.MenuIdList)
                    {
                        List<long> TemplistSon = await GetAllSonId(menuId);
                        if (TemplistSon != null)
                        {
                            Templist.AddRange(TemplistSon);
                        }
                    }
                    input.MenuIdList = Templist;
                }
                else
                {
                    input.MenuIdList = await GetAllSonId(input.MenuId);
                }
            }
            input.Sorting = input.Sorting.IsNullOrEmpty() ? "Order desc" : input.Sorting;          // 默认排序
            Func<IQueryable<Content>, IQueryable<Content>> func = (q) =>
            {
                // 筛选栏目信息
                q = (!input.MenuIdList.IsNullOrEmpty() && input.MenuIdList.Count > 0) ?
                         q.Where(t => input.MenuIdList.Contains(t.MenuId) && t.IsActive):
                         q.Where(t => t.MenuId == input.MenuId && t.IsActive)
                        .Where(t => t.RelateId == input.RelateId);
                q = q.WhereIf(!input.IsHomeRecommend.IsNullOrEmpty(), t => t.IsHomeRecommend == (input.IsHomeRecommend == "1"))
                     .WhereIf(!input.Bool1.IsNullOrEmpty(), t => t.Bool1 == (input.Bool1 == "1"))
                     .WhereIf(!input.Bool2.IsNullOrEmpty(), t => t.Bool2 == (input.Bool2 == "1"))
                     .WhereIf(!input.Str1.IsNullOrEmpty(), t => t.Str1 == input.Str1)
                     .WhereIf(!input.Str2.IsNullOrEmpty(), t => t.Str2 == input.Str2)
                     .WhereIf(!input.Str3.IsNullOrEmpty(), t => t.Str3 == input.Str3)
                     .WhereIf(!input.Str4.IsNullOrEmpty(), t => t.Str4 == input.Str4)
                     .WhereIf(!input.Str5.IsNullOrEmpty(), t => t.Str5 == input.Str5)
                     .WhereIf(!input.Filter.IsNullOrEmpty(), t => t.Title.Contains(input.Filter) || t.Body.Contains(input.Filter));
                q = _contentFrontendManager.GetOrderedQuery(input.Sorting, q);
                return q;
            };

            var topCount = input.IMustHavePic.HasValue && input.IMustHavePic.Value ? 0 : 1;                 // 如果过滤图片则获取全部数据再做筛选
            var list = await _contentFrontendManager.GetAllContentAsync<_ContentDto>(func, topCount);

            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Body))
                {
                    item.Body = item.Body.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                if (!string.IsNullOrEmpty(item.Body2))
                {
                    item.Body2 = item.Body2.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                item.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(item.MenuId)).DisplayName();   // 栏目名称
                item.ListUrl = await _urlHelper.GetUrl(item.MenuId);                   
                if (!string.IsNullOrEmpty(item.Str2) && item.Str2.ToLower().Contains("http"))
                {
                    item.LinkUrl = item.Str2;
                }
                else
                {
                    item.LinkUrl = await _urlHelper.GetUrl(item.MenuId, item.AuxiliaryId);
                }
                // 详情页URL
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    item.DicPic = await _GetPicOrFileDic(input.PicKeys, item.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    //item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, input.PicListMaxCount);
                    var list_count = input.PicListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, max);
                    }
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    item.DicFile = await _GetPicOrFileDic(input.FileKeys, item.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    //item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, input.FileListMaxCount);
                    var list_count = input.FileListMaxCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var maxC in list_count)
                    {
                        int.TryParse(maxC, out int max);
                        item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, max);
                    }
                }
            }
            list = (input.IMustHavePic.HasValue && input.IMustHavePic.Value) ?
                     list.Where(t => t.DicPic != null && t.DicPic.Count > 0).ToList() : list;   // 筛选有图的数据
            if (list != null&&list.Count>0)
            {
                var result = list.FirstOrDefault();
                var tempInput = new _ContentInput {
                    Id=result.AuxiliaryId,
                    RelateId= input.RelateId,
                    PicKeys=input.PicKeys,
                    PicListKeys=input.PicListKeys,
                    PicListMaxCount=input.PicListMaxCount,
                    FileKeys=input.FileKeys,
                    FileListKeys=input.FileListKeys,
                    FileListMaxCount=input.FileListMaxCount,
                    Sorting =input.Sorting,
                    ShowPreAndNextInfo=false
                };
                return await _GetContentAsync(tempInput);
            }
            else {
                return new _ContentDto();
            }
        }

        /// <summary>
        /// 获取n个头条内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns>topcount=0时获取所有数据</returns>
        public async Task<List<_ContentListDto>> _GetTopContentAsync(_TopContentInput input)
        {
            // 是否查找子栏目
            if (input.IsAllSon)
            {
                
                if (input.MenuIdList != null)
                {
                    //递归遍历所有子级
                    List<long> Templist = new List<long>();
                    foreach (var menuId in input.MenuIdList)
                    {
                        var idTraceItem = await _menuStore.GetMenuIdTraceCacheItemAsync(menuId);
                        var TemplistSon = await _menuStore.GetAllSonMenuItemIdAsync(idTraceItem, true);
                        if (TemplistSon != null)
                        {
                            Templist.AddRange(TemplistSon);
                        }
                    }
                    input.MenuIdList = Templist;
                }
                else
                {
                    var idTraceItem = await _menuStore.GetMenuIdTraceCacheItemAsync(input.MenuId);
                    var idList = await _menuStore.GetAllSonMenuItemIdAsync(idTraceItem, true);
                    if (idList != null)
                    {
                        input.MenuIdList = idList.ToList();
                    }
                }
            }
            long LongNowTime = DateTime.Now.ToUnixTimeByMilliseconds();
            input.Sorting = input.Sorting.IsNullOrEmpty() ? "Order desc" : input.Sorting;          // 默认排序
            Func<IQueryable<Content>, IQueryable<Content>> func = (q) =>
            {
                // 筛选栏目信息
                q = (!input.MenuIdList.IsNullOrEmpty() && input.MenuIdList.Count > 0) ?
                         q.Where(t => input.MenuIdList.Contains(t.MenuId) && t.IsActive && LongNowTime >= t.Time1) :
                         q.Where(t => t.MenuId == input.MenuId && t.IsActive && LongNowTime >= t.Time1)
                        .Where(t => t.RelateId == input.RelateId);

                q = q.WhereIf(!input.ExcludeIds.IsNullOrEmpty(),t=>!input.ExcludeIds.Contains(t.AuxiliaryId+""))
                     .WhereIf(!input.IsHomeRecommend.IsNullOrEmpty(), t => t.IsHomeRecommend == (input.IsHomeRecommend == "1"))
                     .WhereIf(!input.Bool1.IsNullOrEmpty(), t => t.Bool1 == (input.Bool1 == "1"))
                     .WhereIf(!input.Bool2.IsNullOrEmpty(), t => t.Bool2 == (input.Bool2 == "1"))
                     .WhereIf(!input.Bool3.IsNullOrEmpty(), t => t.Bool3 == (input.Bool3 == "1"))
                     .WhereIf(!input.Str1.IsNullOrEmpty(), t => t.Str1 == input.Str1)
                     .WhereIf(!input.Str2.IsNullOrEmpty(), t => t.Str2 == input.Str2)
                     .WhereIf(!input.Str3.IsNullOrEmpty(), t => t.Str3 == input.Str3)
                     .WhereIf(!input.Str4.IsNullOrEmpty(), t => t.Str4 == input.Str4)
                     .WhereIf(!input.Str5.IsNullOrEmpty(), t => t.Str5 == input.Str5)
                     .WhereIf(!input.Filter.IsNullOrEmpty(), t => t.Title.Contains(input.Filter) || t.Body.Contains(input.Filter));
                q = _contentFrontendManager.GetOrderedQuery(input.Sorting, q);
                return q;
            };
            var topCount = input.IMustHavePic.HasValue && input.IMustHavePic.Value ? 0 : input.TopCount;    // 如果过滤图片则获取全部数据再做筛选
            var list = await _contentFrontendManager.GetAllContentAsync<_ContentListDto>(func, topCount);

            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Body))
                {
                    item.Body = item.Body.Replace("[FileBaseUrl]", _WebUrlService.FileServerRootAddress);
                }
                item.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(item.MenuId)).DisplayName();   // 栏目名称
                item.ListUrl = await _urlHelper.GetUrl(item.MenuId);                                        // 列表页URL
                if (!string.IsNullOrEmpty(item.Str2) && item.Str2.ToLower().Contains("http"))
                {
                    item.LinkUrl = item.Str2;
                }
                else
                {
                    item.LinkUrl = await _urlHelper.GetUrl(item.MenuId, item.AuxiliaryId);
                }
                                   // 详情页URL
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    item.DicPic = await _GetPicOrFileDic(input.PicKeys, item.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, input.PicListMaxCount);
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    item.DicFile = await _GetPicOrFileDic(input.FileKeys, item.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, input.FileListMaxCount);
                }
            }
            list = (input.IMustHavePic.HasValue && input.IMustHavePic.Value && input.TopCount != 0) ?
                     list.Where(t => t.DicPic != null && t.DicPic.Count > 0).Take(input.TopCount).ToList() : list;   // 筛选有图的数据
            return list;
        }


        /// <summary>
        /// 获取所有大事记
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>


        public async Task<List<_EventsContentListDto>> _GetAllEventsContentAsync(_EventsContentInput input)
        {
            long LongNowTime = DateTime.Now.ToUnixTimeByMilliseconds();
            input.Sorting = input.Sorting.IsNullOrEmpty() ? "Order desc" : input.Sorting;          // 默认排序
            Func<IQueryable<Content>, IQueryable<Content>> func = (q) =>
            {
                // 筛选栏目信息
                q =  q.Where(t => t.MenuId == input.MenuId && t.IsActive && LongNowTime >= t.Time1)
                      .Where(t => t.RelateId == input.RelateId);
                q = q.WhereIf(!input.ExcludeIds.IsNullOrEmpty(), t => !input.ExcludeIds.Contains(t.AuxiliaryId + ""))
                     .WhereIf(!input.IsHomeRecommend.IsNullOrEmpty(), t => t.IsHomeRecommend == (input.IsHomeRecommend == "1"))
                     .WhereIf(!input.Bool1.IsNullOrEmpty(), t => t.Bool1 == (input.Bool1 == "1"))
                     .WhereIf(!input.Bool2.IsNullOrEmpty(), t => t.Bool2 == (input.Bool2 == "1"))
                     .WhereIf(!input.Bool3.IsNullOrEmpty(), t => t.Bool3 == (input.Bool3 == "1"))
                     .WhereIf(!input.Str1.IsNullOrEmpty(), t => t.Str1 == input.Str1)
                     .WhereIf(!input.Str2.IsNullOrEmpty(), t => t.Str2 == input.Str2)
                     .WhereIf(!input.Str3.IsNullOrEmpty(), t => t.Str3 == input.Str3)
                     .WhereIf(!input.Str4.IsNullOrEmpty(), t => t.Str4 == input.Str4)
                     .WhereIf(!input.Str5.IsNullOrEmpty(), t => t.Str5 == input.Str5)
                     .WhereIf(!input.Filter.IsNullOrEmpty(), t => t.Title.Contains(input.Filter) || t.Body.Contains(input.Filter));
                q = _contentFrontendManager.GetOrderedQuery(input.Sorting, q);
                return q;
            };
            var list = await _contentFrontendManager.GetAllContentAsync<_EventsContentListDto>(func);

            foreach (var item in list)
            {
                item.Year = item.PublishTime.FromUnixTimestampByMilliseconds().ToLocalTime().Year;
                double ss= Math.Round((Convert.ToDouble(item.PublishTime.FromUnixTimestampByMilliseconds().ToLocalTime().Month) / Convert.ToDouble(3)), 2);
                item.Quarter= Convert.ToInt32(Math.Ceiling(ss));
                item.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(item.MenuId)).DisplayName();   // 栏目名称
                item.ListUrl = await _urlHelper.GetUrl(item.MenuId);                                        // 列表页URL
                item.LinkUrl = await _urlHelper.GetUrl(item.MenuId, item.AuxiliaryId);                     // 详情页URL
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    item.DicPic = await _GetPicOrFileDic(input.PicKeys, item.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, input.PicListMaxCount);
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    item.DicFile = await _GetPicOrFileDic(input.FileKeys, item.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, input.FileListMaxCount);
                }
            }
          
            return list;
        }


        /// <summary>
        /// 获取分页的内容信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<_ContentListDto>> _GetPagedContentAsync(_PagedContentInput input)
        {
            var needCache = await SettingManager.GetSettingValueAsync<bool>(MtAppSettings.General.CacheListResult);
            if (needCache && input.Filter.IsNullOrEmpty())
            {
                var key = input.ToJsonString().ToMd5();
                return await PagedListCache.GetAsync(key, async () =>
                {
                    return await _GetPagedContentInternalAsync(input);
                });
            }
            else
            {
                return await _GetPagedContentInternalAsync(input);
            }
        }
        private async Task<PagedResultDto<_ContentListDto>> _GetPagedContentInternalAsync(_PagedContentInput input)
        {
            // 是否查找子栏目
            if (input.IsAllSon && input.MenuIdList != null)
            {
                List<long> Templist = new List<long>();
                foreach (var menuId in input.MenuIdList)
                {
                    var idList = await GetAllSonId(menuId);
                    Templist.AddRange(idList);
                }
                input.MenuIdList = Templist;
            }
            else if (input.IsAllSon)
            {
                input.MenuIdList = await GetAllSonId(input.MenuId);
            }
            input.Sorting = input.Sorting.IsNullOrEmpty() ? "Order desc" : input.Sorting;          // 默认排序
            var startTime = input.Year.HasValue ? ConvertYearToLong(input.Year.Value) : 0;
            var endTime = input.Year > 0 ? ConvertYearToLong(input.Year.Value + 1) : 0;
            long LongNowTime = DateTime.Now.ToUnixTimeByMilliseconds();
            List<long> exAuxIds = new List<long>();
            if (!string.IsNullOrEmpty(input.ExcludeIds))
            {
                exAuxIds = input.ExcludeIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();
            }
            Func<IQueryable<Content>, IQueryable<Content>> func = (q) =>
            {
                // 筛选栏目信息
                q = (!input.MenuIdList.IsNullOrEmpty() && input.MenuIdList.Count > 0) ?
                         q.Where(t => input.MenuIdList.Contains(t.MenuId) && t.IsActive && LongNowTime >= t.Time1) :
                         q.Where(t => t.MenuId == input.MenuId && t.IsActive && LongNowTime >= t.Time1);
                q = q.Where(t => t.RelateId == input.RelateId);

                // 其他过滤条件
                q = q.WhereIf(!exAuxIds.IsNullOrEmpty(), t => !exAuxIds.Contains(t.AuxiliaryId))
                     .WhereIf(!input.IsHomeRecommend.IsNullOrEmpty(), t => t.IsHomeRecommend == (input.IsHomeRecommend == "1"))
                     .WhereIf(input.Year.HasValue, t => t.PublishTime >= startTime && t.PublishTime < endTime)
                     .WhereIf(!input.Bool1.IsNullOrEmpty(), t => t.Bool1 == (input.Bool1 == "1"))
                     .WhereIf(!input.Bool2.IsNullOrEmpty(), t => t.Bool2 == (input.Bool2 == "1"))
                     .WhereIf(!input.Str1.IsNullOrEmpty(), t => t.Str1 == input.Str1)
                     .WhereIf(!input.Str2.IsNullOrEmpty(), t => t.Str2 == input.Str2)
                     .WhereIf(!input.Str3.IsNullOrEmpty(), t => t.Str3 == input.Str3)
                     .WhereIf(!input.Str4.IsNullOrEmpty(), t => t.Str4 == input.Str4)
                     .WhereIf(!input.Str5.IsNullOrEmpty(), t => t.Str5 == input.Str5)
                     .WhereIf(!input.Str6.IsNullOrEmpty(), t => t.Str6 == input.Str6)
                     .WhereIf(!input.Str7.IsNullOrEmpty(), t => t.Str7.Contains("," + input.Str7 + ","))
                     .WhereIf(!input.Str8.IsNullOrEmpty(), t => t.Str8.Contains("," + input.Str8 + ","))
                     .WhereIf(!input.Str9.IsNullOrEmpty(), t => t.Str9.Contains("," + input.Str9 + ","))
                     .WhereIf(!input.Filter.IsNullOrEmpty(), t => t.Title.Contains(input.Filter) || t.Body.Contains(input.Filter));
                q = _contentFrontendManager.GetOrderedQuery(input.Sorting, q);
                return q;
            };

            var pagedData = await _contentFrontendManager.GetContentListByPagedAsync<_ContentListDto>(func, input.SkipCount, input.MaxResultCount);
            var result = new PagedResultDto<_ContentListDto>(pagedData.TotolCount, pagedData.Items);
            foreach (var item in result.Items)
            {
                item.KindName = (await _menuStore.GetMenuIdTraceCacheItemAsync(item.MenuId)).DisplayName();   // 栏目名称
                item.ListUrl = await _urlHelper.GetUrl(item.MenuId);                                        // 列表页URL
                item.LinkUrl = await _urlHelper.GetUrl(item.MenuId, item.AuxiliaryId);                     // 详情页URL
                if (string.IsNullOrEmpty(item.Str1) && !string.IsNullOrEmpty(item.Body))
                {
                    item.Str1 = StripHTML(item.Body);
                }
                // 图片
                if (!input.PicKeys.IsNullOrEmpty())
                {
                    item.DicPic = await _GetPicOrFileDic(input.PicKeys, item.Id);
                }
                // 图片列表
                if (!input.PicListKeys.IsNullOrEmpty())
                {
                    item.DicPicList = await _GetPicsOrFilesDic(input.PicListKeys, item.Id, input.PicListMaxCount);
                }
                // 单文件
                if (!input.FileKeys.IsNullOrEmpty())
                {
                    item.DicFile = await _GetPicOrFileDic(input.FileKeys, item.Id);
                }
                // 多文件列表
                if (!input.FileListKeys.IsNullOrEmpty())
                {
                    item.DicFileList = await _GetPicsOrFilesDic(input.FileListKeys, item.Id, input.FileListMaxCount);
                }
            }
            return result;
        }

        /// <summary>
        /// 更新点击
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> _UpdateHitAsync(_ContentIdInput input)
        {
            var open = await SettingManager.GetSettingValueAsync<bool>(MtAppSettings.General.RecordClicks);
            if (open)
            {
                return await _contentFrontendManager.UpdatePv(input.Id);
            }
            return 1;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="input">上下页的模型</param>
        /// <returns></returns>
        public async Task<_PreAndNextDto> _GetPreAndNextContentAsync(_PreAndNextInput input)
        {
            var result = new _PreAndNextDto();
            var link = await _contentFrontendManager.GetPreAndNextLink(input.Sorting, input.MenuId, input.RelateId, input.Id);
            if (link != null)
            {
                if (link.NextAuxiliaryId > 0)
                {
                    var nextData = await _contentFrontendManager.GetContentByIdAsync<_ContentDto>(link.NextAuxiliaryId);
                    if (nextData != null && !string.IsNullOrEmpty(nextData.Str2) && nextData.Str2.ToLower().Contains("http"))
                    {
                        result.NextLink = nextData.Str2;
                    }
                    else
                    {
                        result.NextLink = await _urlHelper.GetUrl(input.MenuId, link.NextAuxiliaryId);
                    }
                    
                    result.NextTitle = nextData.Title;
                }
                if (link.PreAuxiliaryId > 0)
                {
                    var preData = await _contentFrontendManager.GetContentByIdAsync<_ContentDto>(link.PreAuxiliaryId);
                    if (preData != null && !string.IsNullOrEmpty(preData.Str2) && preData.Str2.ToLower().Contains("http"))
                    {
                        result.PreLink = preData.Str2;
                    }
                    else
                    {
                        result.PreLink = await _urlHelper.GetUrl(input.MenuId, link.PreAuxiliaryId);
                    }
                    
                    result.PreTitle = preData.Title;
                }
            }
            return result;
        }

        public async Task<Dictionary<string, List<FileObjectDto>>> _GetPicOrFileDics(string keys, Guid Id, int maxCount)
        {
            return await _GetPicsOrFilesDic(keys, Id, maxCount);
        }

        #endregion


        /// <summary>
        /// 根据Guid 获取 AuxiliaryId
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<long> _GetLongIdAsync(Guid id)
        {
            var result = await _contentFrontendManager.GetLongIdAsync(id);
            return result;
        }


        #region 私有方法
        /// <summary>
        /// 获取单图片或单文件字典
        /// </summary>
        /// <param name="keys">关键字（多个使用逗号分隔）</param>
        /// <param name="Id">内容ID</param>
        /// <returns></returns>
        private async Task<Dictionary<string, FileObjectDto>> _GetPicOrFileDic(string keys, Guid Id)
        {
            var dic = new Dictionary<string, FileObjectDto>();
            var list = keys.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var picList = await _fileObjectManager.GetListByContentId(Id, list);             // 查找文件
            if (picList != null)
            {
                foreach (var key in list)
                {
                    var pic = picList.FirstOrDefault(t => t.Alias == key);             // 查找文件
                    if (pic != null)
                    {
                        var item = pic;
                        if (!string.IsNullOrEmpty(item.FileUrl) && !item.FileUrl.Contains("/mtsc/uploads"))
                        {
                            item.FileUrl = _WebUrlService.FileServerRootAddress + item.FileUrl;
                        }
                        if (!string.IsNullOrEmpty(item.PreViewImage) && !item.PreViewImage.Contains("/mtsc/uploads"))
                        {
                            item.PreViewImage = _WebUrlService.FileServerRootAddress + item.PreViewImage;
                        }
                        dic[key] = ObjectMapper.Map<FileObjectDto>(item);// 更新字典            // 更新字典
                    }
                }
            }
            return dic;
        }

        /// <summary>
        /// 获取图片列表或文件列表字典
        /// </summary>
        /// <param name="keys">关键字（多个使用逗号分隔）</param>
        /// <param name="Id">内容ID</param>
        /// <param name="maxCount">最大加载条数</param>
        /// <returns></returns>
        private async Task<Dictionary<string, List<FileObjectDto>>> _GetPicsOrFilesDic(string keys, Guid Id, int maxCount)
        {
            var list = keys.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var dicList = new Dictionary<string, List<FileObjectDto>>();
            foreach (var key in list)
            {
                var fileList = await _fileObjectManager.GetListByContentId(Id, key, maxCount);   // 查找文件
                if (fileList != null && fileList.Count>0)
                {
                    foreach (var item in fileList)
                    {
                        if (!string.IsNullOrEmpty(item.FileUrl) && !item.FileUrl.Contains("/mtsc/uploads"))
                        {
                            item.FileUrl = _WebUrlService.FileServerRootAddress + item.FileUrl;
                        }
                        if (!string.IsNullOrEmpty(item.PreViewImage) && !item.PreViewImage.Contains("/mtsc/uploads"))
                        {
                            item.PreViewImage = _WebUrlService.FileServerRootAddress + item.PreViewImage;
                        }
                    }
                    dicList[key] = ObjectMapper.Map<List<FileObjectDto>>(fileList);   // 更新字典
                }
            }
            return dicList;
        }

        /// <summary>
        /// 年份转unixTime
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        private long ConvertYearToLong(int year)
        {
            DateTime startTime = Clock.Normalize(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            DateTime time = Clock.Normalize(new System.DateTime(year, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;            //除10000调整为13位
            return t;
        }
        #endregion


        #region 扩展方法
        /// <summary>
        /// 递归获取所有后代的栏目id
        /// 创建日期：2020年04月29日
        /// 创建人：WUJB
        /// </summary>
        /// <param name="MenuId">栏目Id</param>
        /// <returns></returns>
        private async Task<List<long>> GetAllSonId(long MenuId)
        {
            var idTraceItem = await _menuStore.GetMenuIdTraceCacheItemAsync(MenuId);
            return await _menuStore.GetAllSonMenuItemIdAsync(idTraceItem, true);
        }

        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="html">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        private string StripHTML(string html)
        {
            int length = 100;
            html = HttpUtility.HtmlDecode(html);
            string strText = Regex.Replace(html, "<[^>]+>", "");
            strText = Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }


        /// <summary>
        /// 获取编辑器中图片
        /// </summary>
        /// <param name="sHtmlText"></param>
        /// <returns></returns>
        public static string ReplaceImg(string sHtmlText)
        {
            string IMGURL = "";
            if (string.IsNullOrEmpty(sHtmlText))
            {
                return "";
            }
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);

            string[] sUrlList = new string[matches.Count];
            // 取得匹配项列表 
            foreach (Match match in matches)
            {
                IMGURL = match.Groups["imgUrl"].Value;
                if (!string.IsNullOrEmpty(IMGURL))
                {
                    break;
                }
            }
            return IMGURL;
        }
        #endregion

        //public async Task GetAllTestAsync()
        //{
        //    var data = await _contentBaseRepository.GetAllListAsync();
        //}
    }
}
